//
//  UIImage+ImageEffect.swift
//  weibobbaj
//
//  Created by Tiffany宝 on 16/4/25.
//  Copyright © 2016年 Tiffany. All rights reserved.
//

import UIKit

extension UIImage {
    
    // MARK: - 拉伸图片的方法
    class func scalePic(imageStr: String) -> UIImage{
        
        var image = (UIImage(named: imageStr))!
        image = image.resizableImageWithCapInsets(UIEdgeInsets(top: image.size.height / 2, left: image.size.width / 2, bottom: image.size.height / 2, right: image.size.width / 2))
        return image
    }

    
    //缩放图片
    func scaleToWidth(width: CGFloat) -> UIImage{
        
        if self.size.width < width{
            
            return self
        }
        
        let height = width * self.size.height / self.size.width
        
        let rect = CGRectMake(0, 0, width, height)
        
        //开启图形上下文  --  (2句代码实现的效果一样)
        UIGraphicsBeginImageContext(rect.size)
//        UIGraphicsBeginImageContextWithOptions(rect.size, false, 1)
        
        //渲染
        self.drawInRect(rect)
        
        //获取图片
        let image = UIGraphicsGetImageFromCurrentImageContext()
        
        //关闭图形上下文
        UIGraphicsEndImageContext()
        
        //返回图片
        return image
    }
    
    //截取屏幕
    class func getCurrentImage() -> UIImage{
        
        let window = UIApplication.sharedApplication().keyWindow
        //开启图形上下文
        // 参数3： 传入0，代表是屏幕真实大小截图，传1的话，以点坐标的大小
        UIGraphicsBeginImageContextWithOptions(window!.bounds.size, false, 1)
        
        //把屏幕内容渲染到图形上下文
        window?.drawViewHierarchyInRect(window!.bounds, afterScreenUpdates: true)
        
        //获取图片
        let image = UIGraphicsGetImageFromCurrentImageContext()
        
        //关闭图形上下文
        UIGraphicsEndImageContext()
        
        //返回图片
        return image
    }
}